<template>
  <div class="login-wrap" v-loading="loading">
    <div class="ms-login">
      <!-- <div class="ms-title">系统名称</div> -->
      <div class="login-header">
        <div class="login-header-logo">
          <img :src="'img/login/bus-logo.jpeg'" :width="72" :height="72" />
        </div>
        <div class="login-header-title">基于PYTHONBLOG分析系统</div>
      </div>
      <el-form
        :model="loginForm"
        :rules="loginRule"
        ref="loginForm"
        label-width="0px"
        class="ms-content"
      >
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入帐号">
            <img
              slot="prefix"
              src="img/login/user.png"
              :width="15"
              :height="15"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            placeholder="请输入密码"
            v-model="loginForm.password"
            @keyup.enter.native="submitForm('loginForm')"
          >
            <img
              slot="prefix"
              src="img/login/pass.png"
              :width="15"
              :height="15"
            />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="login-tips-wrapper">
          <div class="login-tips" @click="registerShow">注册账户</div>
        </el-form-item>
      </el-form>
    </div>
    <el-card class="box-card" v-show="isRegisterShow">
      <div slot="header" class="clearfix">
        <span>注册用户</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="registerShow"
        >
          <i class="el-icon-close"></i>
        </el-button>
      </div>
      <el-form
        :model="registerForm"
        status-icon
        :rules="registerRule"
        ref="registerForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="帐号"
          prop="email"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            {
              type: 'email',
              message: '请输入正确的邮箱地址',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="registerForm.email"></el-input>
        </el-form-item>
        <el-form-item label="用户类别" prop="type">
          <el-select v-model="registerForm.type" placeholder="请选择用户类别">
            <el-option label="用户" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input
            type="password"
            v-model="registerForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input
            type="password"
            v-model="registerForm.checkPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="registerDom('registerForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('registerForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data: function () {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.registerForm.checkPass !== "") {
          this.$refs.registerForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.registerForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      //定义规则
      let reg = /^1[345789]\d{9}$/;
      if (value === "" || reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的手机号"));
      }
    };
    return {
      registerForm: {
        pass: "",
        checkPass: "",
        email: "",
      },
      registerRule: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
      },
      loginForm: {
        username: "",
        password: "",
      },
      loginRule: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
            type: "email",
          },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      isRegisterShow: false,
      loading: false,
    };
  },
  methods: {
    loginSuccess(data) {
      this.$message({
        message: "登录成功",
        type: "success",
      });
      data.time = Number(new Date());
      this.$store.dispatch("login", data);
      // this.$router.push("/home");
      this.$router.go(-1);
    },
    loginError(info) {
      this.$message.error(info || "登录失败");
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          // this.getLogin()

          let params = {
            email: this.loginForm.username,
            password: this.loginForm.password,
          };
          console.info("登录参数:", params);
          this.$axios
            .post("/user/login/", params)
            .then((res) => {
              console.log(res);
              if (res.status === 200) {
                window.sessionStorage.setItem(
                  "token",
                  res.config.xsrfCookieName
                );
                // window.sessionStorage.setItem('user', {
                //   id: res.data.id,
                //   name: res.data.name,
                //   password: res.data.password,
                //   u_type: res.data.u_type,
                //   sex: res.data.sex
                // })
                window.sessionStorage.setItem("userID", res.data.id);
                window.sessionStorage.setItem("userName", res.data.name);
                window.sessionStorage.setItem("userImg", res.data.avatar);
                window.sessionStorage.setItem("userType", res.data.u_type);
                window.sessionStorage.setItem(
                  "userInfo",
                  JSON.stringify(res.data)
                );
                this.$router.push({ name: "all-notes" });
                this.$message.success("登录成功");
                this.loading = false;
              } else {
                console.log(res);
                this.$message({
                  type: "error",
                  message: res.response.status,
                });
              }
            })
            .catch((res) => {
              this.loading = false;
              this.$message.error(res.response.data.message);
            });
        } else {
          return false;
        }
      });
    },
    // 请求登录
    async getLogin() {
      const params = {
        email: this.loginForm.username,
        password: this.loginForm.password,
      };
      const data = await this.$axios.post("/user/login/", params);
      console.log(data);
    },
    registerDom(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          let params = {
            email: this.registerForm.email,
            password: this.registerForm.pass,
            pwd: this.registerForm.checkPass,
          };
          console.info("注册参数:", params);
          this.$axios
            .post(`/user/join/`, params)
            .then((ret) => {
              this.$message({
                message: "注册成功，正在前往登录",
                type: "success",
              });
              setTimeout(() => {
                window.location.reload();
              }, 2000);
            })
            .catch((res) => {
              this.$message.error(res.response.data.message);
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    registerShow() {
      this.isRegisterShow = !this.isRegisterShow;
    },
  },
};
</script>

<style lang="scss" scoped>
.login-wrap {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url(../assets/img/login_bg.png);
  background-repeat: no-repeat;
  // background-size: auto 100%;
  background-size: cover;
}
.login-header {
  margin-top: 150px;
  margin-bottom: 20px;
  text-align: center;
}
.login-header-title {
  color: #ffffff;
  font-size: 32px;
  line-height: 72px;
}
.login-header-logo,
.login-header-title {
  vertical-align: middle;
}
.login-header-logo img {
  border-radius: 50%;
}
.ms-content {
  width: 386px;
  margin: 0 auto;
}
.ms-content .el-button--primary {
  width: 100%;
  color: #ffffff;
  background-color: #0273ff;
  border-color: #0273ff;
}
.ms-content .el-button--primary:hover {
  background-color: #358fff;
}
.ms-content .el-button {
  font-size: 16px;
  color: #ffffff;
}
.ms-content .el-input__prefix {
  border-right: 1px solid rgba(25, 25, 25, 0.2);
}
.ms-content .el-input__prefix img {
  position: relative;
  top: 2px;
  left: 5px;
  border-right: 1px solid rgba(25, 25, 25, 0.2);
  padding-right: 12px;
}

.login-tips {
  display: inline-block;
  font-size: 15px;
  line-height: 30px;
  color: #909399;
  text-align: right;
  cursor: pointer;
  &:hover {
    text-decoration-line: underline;
  }
}
.text {
  font-size: 14px;
}
.item {
  padding: 18px 0;
}
.box-card {
  position: absolute;
  width: 480px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.login-tips-wrapper {
  text-align: right;
}
</style>
<style>
.ms-content .el-input__inner {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.8);
  background-color: #ffffff;
}
.ms-content .el-input--prefix .el-input__inner {
  padding-left: 47px;
}
.ms-content .el-form-item__error {
  color: #f5222d;
  font-size: 14px;
}
.ms-content input::-webkit-input-placeholder {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.4);
}
</style>
